var Promise =   require("../util/xpromise");
var ReqMessage = require("./reqMessage");

var ServantProxy    =   function() {
    this._name  =   undefined;
    this._worker    =   undefined;
    this._rpc       =   undefined;
}

module.exports  =   ServantProxy;

ServantProxy.prototype.__defineGetter__("rpc", function() { return this._rpc; })

ServantProxy.prototype.setTimeout = function(iTimeout) {
    this._worker.timeout = iTimeout;
}

ServantProxy.prototype.setProtocol = function(protocol) {
    this._worker.setProtocol(protocol);
}

ServantProxy.prototype.rpc_call =   function(requestId, funcName, appBuffer) {
    var argsLen = arguments.length;
    var args;
    if(argsLen > 2) {
        args = new Array(argsLen - 2);
        for(var i = 2; i < argsLen; i++) {
            args[i - 2] = arguments[i];
        }
    } else {
        args = [];
    }

    var reqMessage  = new ReqMessage();
    reqMessage.request.iRequestId   =   requestId;
    reqMessage.request.sFuncName    =   funcName;
    reqMessage.request.appBuffer    =   appBuffer;
    reqMessage.request.property     =   {};
    reqMessage.promise              =   Promise.defer();
    reqMessage.worker               =   this._worker;
    reqMessage.setTimeout(this._worker._iTimeout);

    return this._worker.invoke(reqMessage).then(function(data) {
        var response = {
            costtime : 0
        };
        if(data.request && data.request.costtime) {
            response.costtime = data.request.costtime;
        }
        response.appBuffer = data.response;

        return { request:data.request, response:response };
    }, function(data) {
        var response = {
            costtime : 0
        };
        if(data.request && data.request.costtime) {
            response.costtime = data.request.costtime;
        }
        response.error  =   data.error;

        throw { request:data.request, response:response };
    })
}